package com.wenwei.activity;

import android.os.Bundle;
import android.os.Message;
import android.text.TextUtils;
import android.view.View;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;

import com.alipay.sdk.app.AuthTask;
import com.jaeger.library.StatusBarUtil;
import com.jakewharton.rxbinding.widget.RxTextView;
import com.orhanobut.logger.Logger;
import com.umeng.message.PushAgent;
import com.wenwei.bean.ALiInfoBean;
import com.wenwei.bean.LoginBean;
import com.wenwei.bean.PayResult;
import com.wenwei.bean.ThreadLoginBean;
import com.wenwei.bean.ThreadUserInfo;
import com.wenwei.net.ApiManager;
import com.wenwei.net.BaseSubscriber;
import com.wenwei.parking.BaseActivity;
import com.wenwei.parking.Constant;
import com.wenwei.parking.R;
import com.wenwei.utils.AccountValidatorUtil;
import com.wenwei.utils.AuthResult;
import com.wenwei.utils.RogerSPUtils;

import org.greenrobot.eventbus.EventBus;

import java.util.HashMap;
import java.util.Map;
import java.util.logging.Handler;
import java.util.logging.LogRecord;

import butterknife.Bind;
import butterknife.ButterKnife;
import butterknife.OnClick;
import cn.sharesdk.framework.Platform;
import cn.sharesdk.framework.PlatformActionListener;
import cn.sharesdk.framework.ShareSDK;
import cn.sharesdk.wechat.friends.Wechat;
import rx.Observable;
import rx.functions.Action1;
import rx.functions.Func2;

/**
 * Created by Administrator on 2017/8/21.
 */
public class LoginActivity extends BaseActivity {
    @Bind(R.id.phone_et)
    EditText phoneEt;
    @Bind(R.id.pw_et)
    EditText pwEt;
    @Bind(R.id.login_btn)
    TextView loginBtn;

    @Override
    public int setLayoutResourceId() {
        return R.layout.activity_login;
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        // TODO: add setContentView(...) invocation
        ButterKnife.bind(this);
        StatusBarUtil.setTranslucentForImageViewInFragment(LoginActivity.this, 0, null);
    }

    @Override
    protected void initView() {
        super.initView();
        Observable<CharSequence> phoneObservable = RxTextView.textChanges(phoneEt);
        Observable<CharSequence> psObservable = RxTextView.textChanges(pwEt);
        Observable.combineLatest(phoneObservable, psObservable, new Func2<CharSequence, CharSequence, Boolean>() {
            @Override
            public Boolean call(CharSequence charSequence, CharSequence charSequence2) {
                return !charSequence.toString().equals("") && !charSequence2.toString().equals("");
            }
        }).subscribe(new Action1<Boolean>() {
            @Override
            public void call(Boolean aBoolean) {
                loginBtn.setEnabled(aBoolean);
                if(aBoolean){
                    loginBtn.setBackgroundResource(R.drawable.button_state_2);
                }else{
                    loginBtn.setBackgroundResource(R.drawable.button_state_1);
                }
            }
        });
    }

    @OnClick({R.id.forget_btn, R.id.login_btn, R.id.register_btn, R.id.login_wei_xin, R.id.login_zhi_fu_bao})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.forget_btn:
                Bundle forgetBundle = new Bundle();
                forgetBundle.putString("type","forget");
                goActivity(mContext,RegisterActivity.class,forgetBundle);
                break;
            case R.id.login_btn:
                if (AccountValidatorUtil.isMobile(phoneEt.getText().toString())){
                    userLogin();
                }else {
                    showToast("手机号格式错误");
                }
                break;
            case R.id.register_btn:
                Bundle registerBundle = new Bundle();
                registerBundle.putString("type","register");
                goActivity(mContext,RegisterActivity.class,registerBundle);
                break;
            case R.id.login_wei_xin:
                weChatLogin();
                break;
            case R.id.login_zhi_fu_bao:
                getAliLoginConfig();
                break;
        }
    }


    BaseSubscriber<LoginBean> loginSubscriber;
    private void userLogin(){
        String userPhone = phoneEt.getText().toString();
        String userPw = pwEt.getText().toString();
        loginSubscriber = new BaseSubscriber<LoginBean>(mContext,true,"请稍后...") {
            @Override
            public void onSuccess(LoginBean s) {
                RogerSPUtils.putObject(mContext, Constant.SP_USER_LOGIN_RESULT,s);
                showToast("登录成功");
                goActivity(mContext,HostActivity.class);
                finish();
            }
        };
        PushAgent m = PushAgent.getInstance(mContext);
        Logger.d("token:"+m.getRegistrationId());
        ApiManager.getInstance().userLogin(loginSubscriber, userPhone, userPw, m.getRegistrationId());
    }

    //支付宝三方登录签名
    private BaseSubscriber<String> aliLoginSb;
    private void getAliLoginConfig(){
        aliLoginSb = new BaseSubscriber<String>(mContext) {
            @Override
            public void onSuccess(String s) {
                authV2(s);
            }
        };
        ApiManager.getInstance().getALiLoginConfig(aliLoginSb);
    }


    //微信三方登录
    private void weChatLogin(){
        Platform wechat= ShareSDK.getPlatform(Wechat.NAME);
        wechat.setPlatformActionListener(new PlatformActionListener() {
            @Override
            public void onComplete(final Platform platform, int i, HashMap<String, Object> hashMap) {
                Logger.d("头像:"+platform.getDb().getUserIcon()+"，名称："+platform.getDb().getUserName()
                +",unionid："+platform.getDb().get("unionid"));
                final String id = platform.getDb().get("unionid");
                runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        ThreadLogin(platform.getDb().getUserName(),platform.getDb().getUserIcon(),id);
                    }
                });

            }

            @Override
            public void onError(Platform platform, int i, Throwable throwable) {
                Logger.d("onError:");
            }

            @Override
            public void onCancel(Platform platform, int i) {
                Logger.d("onCancel:");
            }
        });
        wechat.authorize();
    }


    //三方登录
    private BaseSubscriber<LoginBean> threeSb;
    private void ThreadLogin(final String nick, final String avator, final String threeToken){
        threeSb = new BaseSubscriber<LoginBean>(mContext,true,"请稍后") {
            @Override
            public void onSuccess(LoginBean threadLoginBean) {
                if(threadLoginBean.getUsername() == null || threadLoginBean.getUsername().equals("")){
                    //未绑定手机号
                    Bundle registerBundle = new Bundle();
                    registerBundle.putString("type","bind");
                    registerBundle.putString("uid",threeToken);
                    ThreadUserInfo bb = new ThreadUserInfo();
                    bb.setNikename(nick);
                    bb.setAvator(avator);
                    PushAgent m = PushAgent.getInstance(mContext);
                    bb.setRegistrationId(m.getRegistrationId());
                    bb.setPlatform("android");
                    registerBundle.putSerializable("bean",bb);
                    goActivity(mContext,RegisterActivity.class,registerBundle);
                }else{
                    RogerSPUtils.putObject(mContext, Constant.SP_USER_LOGIN_RESULT,threadLoginBean);
                    showToast("登录成功");
                    goActivity(mContext,HostActivity.class);
                    finish();
                }

            }

            @Override
            public void onError(Throwable e) {
                super.onError(e);
                if(e.getMessage().equals("请先绑定手机号")){
                    Bundle registerBundle = new Bundle();
                    registerBundle.putString("type","bind");
                    registerBundle.putString("bind",threeToken);
                    goActivity(mContext,RegisterActivity.class,registerBundle);
                }

            }
        };

        ApiManager.getInstance().threadLogin(threeSb,threeToken);
    }


    //支付宝登录授权
    public void authV2(final String info) {
        Runnable authRunnable = new Runnable() {

            @Override
            public void run() {
                // 构造AuthTask 对象
                AuthTask authTask = new AuthTask(LoginActivity.this);
                // 调用授权接口，获取授权结果
                Map<String, String> result = authTask.authV2(info, true);
                Logger.d("result:"+result);
                Message msg = new Message();
                msg.what = 99;
                msg.obj = result;
                mPayHandler.sendMessage(msg);
            }
        };
        // 必须异步调用
        Thread authThread = new Thread(authRunnable);
        authThread.start();
    }
    private android.os.Handler mPayHandler = new android.os.Handler() {
        @Override
        public void handleMessage(Message msg) {

            switch (msg.what) {
                case 99: {
                    String payResult = msg.obj.toString();
                    Logger.d("回掉："+payResult);
                    //resultStatus={9000};memo={};result={success=true&auth_code=1af0d91938d64cd2b31f8ae8e84dOB93&result_code=200&alipay_open_id=20881040801133860823354012917593&user_id=2088302449300933}
                    AuthResult authResult = new AuthResult((Map<String, String>) msg.obj, true);
                    showToast("authCode:"+authResult.getAuthCode());
                    getAuthInfo(authResult.getAuthCode());
                    break;
                }
                default:
                    break;
            }


        }
    };


    private BaseSubscriber<ALiInfoBean> aLiInfoBeanBaseSubscriber;
    private void getAuthInfo(final String id){
        aLiInfoBeanBaseSubscriber = new BaseSubscriber<ALiInfoBean>(mContext,true,"请稍后") {
            @Override
            public void onSuccess(ALiInfoBean aLiInfoBean) {
                ThreadLogin(aLiInfoBean.getAlipay_user_userinfo_share_response().getNick_name(),
                        aLiInfoBean.getAlipay_user_userinfo_share_response().getAvatar(),
                        id);
            }
        };
        ApiManager.getInstance().getAuthInfo(aLiInfoBeanBaseSubscriber,id);
    }
}
